<template>
  <div>
    <div class="zong">
      <el-button
        @click="toAdd"
        icon="el-icon-circle-plus"
        type="primary"
        round
        size="small"
        >添加</el-button
      >
      <div class="rightS">
        <div class="widthDiv">
          <el-input
            class="marginLeft"
            v-model="pageParam.username"
            placeholder="请输入内容"
            size="small"
            clearable
          ></el-input>
        </div>

        <el-button
          type="primary"
          icon="el-icon-search"
          @click="toSearch"
          size="small"
          >搜索</el-button
        >
      </div>
    </div>

    <el-table :data="tableData" style="width: 100%" size="small">
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column sortable prop="realname" label="姓名"> </el-table-column>
      <el-table-column
        prop="gender"
        label="性别"
        :filters="[
          { text: '男', value: '男' },
          { text: '女', value: '女' },
        ]"
        :filter-method="filterHandler"
      ></el-table-column>
      <el-table-column prop="telephone" label="手机号"></el-table-column>
      <el-table-column prop="birth" label="出生日期"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="title"
      :visible.sync="visible"
      :before-close="beforeClose"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            type="password"
            v-model="form.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="姓名" :label-width="formLabelWidth" prop="realname"
          ><el-input
            v-model.number="form.realname"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
          <el-radio v-model="form.gender" label="女">女</el-radio>
          <el-radio v-model="form.gender" label="男">男</el-radio>
        </el-form-item>

        <el-form-item
          label="出生日期"
          :label-width="formLabelWidth"
          prop="birth"
        >
          <el-date-picker
            :picker-options="expireTimeOption"
            v-model="form.birth"
            type="date"
            value-format="timestamp"
            placeholder="选择你的生日"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="手机号"
          :label-width="formLabelWidth"
          prop="telephone"
        >
          <!-- min="10000000000"
            max="99999999999" -->
          <el-input
            maxlength="10"
            show-word-limit
            v-model.number="form.telephone"
            type="text"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toCancel">取 消</el-button>
        <el-button type="primary" @click="toSave('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <div class="contentPage">
      <el-pagination
        @current-change="currentChange"
        layout="prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import axios from "../utils/request";

export default {
  data() {
    return {
      deadline: "",
      expireTimeOption: {
        disabledDate(date) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() > Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      birth: "631123200000",
      gender: "",
      title: "添加新用户",
      visible: false,
      form: {},
      formLabelWidth: "120px",
      pageParam: {
        page: 1,
        pageSize: 10,

        username: "",
      },
      total: 0,
      tableData: [],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        realname: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        birth: [{ required: true, message: "请在选择生日", trigger: "change" }],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
      },
    };
  },
  //   created() {

  //   },
  computed: {},
  methods: {
    toSearch() {
      this.pageParam.page = 1;
      this.pageQuery();
    },
    handleDate(value) {
      this.deadline = value;
    },
    filterHandler(value, row, column) {
      const property = column["property"];
      return row[property] === value;
    },
    toCancel() {
      this.$refs["ruleForm"].resetFields();
      this.visible = false;
    },
    beforeClose(done) {
      this.$refs["ruleForm"].resetFields();
      done();
    },
    toAdd() {
      this.form = {};
      this.visible = true;
      this.title = "请添加新用户";
    },
    handleEdit(row) {
      // console.log(index, row);
      this.title = "修改用户信息";

      this.form = { ...row };
      // this.form = row ;
      this.visible = true;
    },

    toSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 校验通过
          // console.log(this.form, "=======");
          axios.post("/baseUser/saveOrUpdate ", this.form).then((res) => {
            if (res.status == 200) {
              // 保存成功，关闭模态框，刷新表格数据
              // alert("保存成功");
              this.$notify({
                title: "成功",
                message: "这是一条成功的提示消息",
                type: "success",
              });
              this.toCancel();
              this.findAll();
            } else {
              // alert("保存失败");
              this.$notify.error({
                title: "错误",
                message: "这是一条错误的提示消息",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    handleDelete(id) {
      // alert(id);
      // id就是要删除的分类的id

      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 属性名和属性一直时可简写
          // axios.get('',{params:{id:id}})  await等后面的异步请求执行成功，拿到成功的结果 然后返回

          let res;
          res = await axios.get("/baseUser/deleteById", { params: { id } });

          this.$notify({
            title: res.status == 200 ? "成功" : "失败",
            message: "res.statusText",
            type: res.status == 200 ? "success" : "error",
          });
          this.findAll();
          // console.log(res);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    findAll() {
      axios.get("baseUser/findAll").then((res) => {
        // console.log(res.data);
        this.tableData = res.data;
      });
    },

    currentChange(val) {
      this.pageParam.page = val;
      this.pageQuery();
    },
    async pageQuery() {
      let res = await axios.get("/baseUser/pageQuery", {
        params: this.pageParam,
      });
      this.tableData = res.data.list.reverse();
      this.total = res.data.total;
    },
  },

  created() {
    this.pageQuery();
    // let res = await axios.get("/baseUser/findAll ");
    // // console.log(res);
    // this.tableData = res.data;
  },
  mounted() {},
};
</script>
<style scoped>
.widthDiv {
  width: 200px;
  display: inline-block;
  margin-right: 10px;
  margin-bottom: 10px;
}
.zong {
  position: relative;
}
.rightS {
  position: absolute;
  left: 71%;
  top: 0;
}
</style>